package servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(urlPatterns = "/add_new.do")
@MultipartConfig
public class AddNewServlet extends HttpServlet {

    // 文件上传目录
    private static final String UPLOAD_DIRECTORY = "uploads";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ServletException {
        // 转发到JSP页面以显示表单（假设有一个add_new.jsp文件）
        req.getRequestDispatcher("/add_new.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取表单参数
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        String content = req.getParameter("content");

        // 处理文件上传
        Part coverFile = req.getPart("coverUrl");
        String fileName = getFileName(coverFile);
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }


        /**
         * 将上传的文件保存到服务器
         *
         */
        try (InputStream inputStream = coverFile.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(uploadPath + File.separator + fileName)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }

        // 您现在可以根据需要使用标题、作者、内容和文件路径
        // 例如，您可以将此信息存储在数据库中

        // 向客户端发送响应
        resp.setContentType("text/html");
        resp.getWriter().println("文件上传和表单数据接收成功。");
    }

    // 获取文件名的辅助方法
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] items = contentDisposition.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename")) {
                return item.substring(item.indexOf('=') + 2, item.length() - 1);
            }
        }
        return "";
    }
}
